#!/bin/bash

# show the command executed by the script
#set -x

PREFIX="\033[;32mINFO: \033[0m"
HEMU=./build/hemu

if [ $# -eq 0 ]; then
	echo "Usage: $0 <CACT source file> options"
	exit 1
fi

mkdir -p ./temp
# substitute the file extension ".cact" with ".ll" in `$1`
hxd1file=${1%.cact}.ll
# remove the path in `hxd1file`
hxd1file=${hxd1file##*/}

echo -e $PREFIX"Compiling CACT file to HXD1 IR..."
./build/compiler $1 -emit-hxd1 $2 -o ./temp/$hxd1file
if [ $? -ne 0 ]; then
	exit $?
fi


cfile=${1%.cact}.c

# remove the path in `cfile`
cfile=${cfile##*/}

exefile=${1%.cact}
exefile=${exefile##*/}


echo -e $PREFIX"Generating C code..."
cat ./test/cactio.c $1 > ./temp/$cfile

echo -e $PREFIX"Compiling C file with gcc..."
gcc ./temp/$cfile -o ./temp/$exefile

if [ $? -ne 0 ]; then
	exit $?
fi

echo -e $PREFIX"Press Enter to start HEMU... "
read -p "> "

$HEMU ./temp/$hxd1file

echo -e $PREFIX"Press Enter to start the ELF file from gcc... "
read -p "> "

./temp/$exefile
